package com.aquarium.bt;

import com.aquarium.alarm.AlarmManager;
import com.aquarium.config.BTDataConfig;
import com.aquarium.sensor.SensorManager;

import android.os.Handler;
import android.os.Message;

public class RecvDataDispatcher {

	private static RecvDataDispatcher mRecvDataDispatcher;
	private DataInterpreter mDataInterpreter;
	private Handler mSensorValueHandler;
	private Handler mAlarmManagerHandler;

	private RecvDataDispatcher() {
		mDataInterpreter = new DataInterpreter();
	}

	public static RecvDataDispatcher getInstance() {
		if (mRecvDataDispatcher == null) {
			mRecvDataDispatcher = new RecvDataDispatcher();
		}
		return mRecvDataDispatcher;
	}

	public void setSensorValueHandler(Handler handler) {
		mSensorValueHandler = handler;
	}

	public void setAlarmManagerHandler(Handler handler) {
		mAlarmManagerHandler = handler;
	}

	/**
	 * When {@link BTManager} received data from remote BT device, it will
	 * invoke this method and pass received data here.
	 * 
	 * @param data
	 *            The data received from remote BT device
	 */
	public void recv(String data) {
		if (mSensorValueHandler == null) {
			return;
		}
		DataStruct struct = mDataInterpreter.unpack(data);
		recv(struct);
		return;
	}

	public void recv(DataStruct struct) {
		Message msg = new Message();
		switch (struct.code) {
		// fake data, here means received sensor value
		case BTDataConfig.RECV_HP_VALUE:
			msg.what = SensorManager.HANDLE_PH_VALUE;
			msg.obj = struct.data;
			mSensorValueHandler.sendMessage(msg);
			break;
		case BTDataConfig.RECV_TEMPERATURE_VALUE:
			msg.what = SensorManager.HANDLE_TEMPERATURE_VALUE;
			msg.obj = struct.data;
			mSensorValueHandler.sendMessage(msg);
			break;
		case BTDataConfig.RECV_OXYGEN_VALUE:
			msg.what = SensorManager.HANDLE_OXYGEN_VALUE;
			msg.obj = struct.data;
			mSensorValueHandler.sendMessage(msg);
			break;
		case BTDataConfig.RECV_CONDUCTIVITY_VALUE:
			msg.what = SensorManager.HANDLE_CONDUCTIVITY_VALUE;
			msg.obj = struct.data;
			mSensorValueHandler.sendMessage(msg);
			break;
		case BTDataConfig.RECV_WATER_LEVEL_VALUE:
			msg.what = SensorManager.HANDLE_WATER_LEVEL_VALUE;
			msg.obj = struct.data;
			mSensorValueHandler.sendMessage(msg);
			break;
		// fake data, here means received alarm set result
		case BTDataConfig.fakeCode2:
			// all of here is fake.
			// We assume we have received PH_Min alarm value
			msg.what = AlarmManager.HANDLE_GET_PH_MIN;
			msg.obj = struct.data;
			mSensorValueHandler.sendMessage(msg);
			break;
		case BTDataConfig.fakeCode3:

			break;
		default:

			break;
		}
	}
}
